#!/bin/bash

# 测试优化后的线程绑核逻辑
# 使用方法: ./test_optimized_binding.sh

echo "=== 测试优化后的线程绑核逻辑 ==="
echo ""

# 检查是否以root权限运行
if [ "$EUID" -ne 0 ]; then
    echo "请以root权限运行此脚本"
    exit 1
fi

# 检查可执行文件是否存在
if [ ! -f "./llc_miss_thread_bind" ]; then
    echo "错误: 找不到 llc_miss_thread_bind 可执行文件"
    echo "请先编译程序: make"
    exit 1
fi

echo "1. 启动测试进程 (stress-ng)"
# 启动stress-ng作为测试进程
stress-ng --cpu 4 --vm 2 --vm-bytes 128M --timeout 60s &
STRESS_PID=$!

# 等待进程启动
sleep 2

echo "2. 运行优化后的线程绑核程序"
echo "参数: 阈值=50M/s, topNum=10, period=1000ms, 关键字=stress-ng"
echo ""

# 运行优化后的程序
./llc_miss_thread_bind 50 10 1000 stress-ng

echo ""
echo "3. 检查线程绑定结果"
echo ""

# 检查stress-ng进程的线程绑定情况
if ps -p $STRESS_PID > /dev/null; then
    echo "Stress-ng进程 (PID: $STRESS_PID) 的线程绑定情况:"
    ps -T -p $STRESS_PID -o pid,tid,psr,comm
    echo ""
    
    # 检查每个线程的CPU亲和性
    echo "各线程的CPU亲和性:"
    for tid in $(ps -T -p $STRESS_PID -o tid | tail -n +2); do
        echo "TID $tid: $(taskset -p $tid 2>/dev/null | cut -d: -f2)"
    done
else
    echo "Stress-ng进程已结束"
fi

echo ""
echo "4. 清理测试进程"
# 清理测试进程
if ps -p $STRESS_PID > /dev/null; then
    kill $STRESS_PID
    echo "已终止stress-ng进程"
fi

echo ""
echo "=== 测试完成 ==="
echo ""
echo "优化特性验证:"
echo "✓ 固定10秒LLC miss率统计"
echo "✓ 活跃度过滤 (缓存访问 >= 10K)"
echo "✓ 互补绑定策略 (高miss率 + 低miss率线程)"
echo "✓ 物理核心级别的线程配对" 